/*
 *  Copyright 2007 Blandware (http://www.blandware.com)
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package com.blandware.atleap.webapp.action.core.sequence;

import com.blandware.atleap.common.Constants;
import com.blandware.atleap.model.core.*;
import com.blandware.atleap.service.core.LookupManager;
import com.blandware.atleap.webapp.util.core.WebappUtil;
import org.apache.struts.tiles.ComponentContext;
import org.apache.struts.tiles.ControllerSupport;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;


/**
 * <p>Sequence list controller. This class is used to check can user create
 * sequences or not.
 * </p>
 * <p><a href="SequenceListController.java.html"><i>View Source</i></a></p>
 *
 * @author Roman Puchkovskiy <a href="mailto:roman.puchkovskiy@blandware.com">
 *         &lt;roman.puchkovskiy@blandware.com&gt;</a>
 * @version : $Revision: 1.2 $ : 2007/12/17 13:38:25 $
 */
public final class SequenceListController extends ControllerSupport {
	//~ Methods ================================================================
	/**
	 * Retrieves sequences from persistence layer and put 'em to the request.
	 *
	 * @param tilesContext   Current tile context
	 * @param request        Current request
	 * @param response       Current response
	 * @param servletContext Current Servlet Context
	 */
	public void execute(ComponentContext tilesContext, HttpServletRequest request, HttpServletResponse response, ServletContext servletContext)
	        throws Exception {

		Long ownerId = (Long) request.getAttribute("ownerId");
		if ( ownerId != null ) {
			ApplicationContext applicationContext = WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext);
			LookupManager lookupManager = (LookupManager) applicationContext.getBean(Constants.LOOKUP_MANAGER_BEAN);
			Localizable owner = lookupManager.retrieveLocalizable(ownerId);

            if (owner instanceof ActionPage) {
                Set identifiers = WebappUtil.getOverridableSequenceIdentifiers(owner, request);
                Map overridenAPSequences = new HashMap();
                List sequences = owner.getSequences();
                for (int i = 0; i < sequences.size(); i++) {
                    Sequence sequence = (Sequence) sequences.get(i);
                    String identifier = sequence.getIdentifier();
                    overridenAPSequences.put(identifier, (identifiers.contains(identifier)) ? Boolean.TRUE : Boolean.FALSE);
                }
                request.setAttribute("overridenAPSequences", overridenAPSequences);
            }

            if (owner instanceof Layout) {
                Set identifiers = WebappUtil.getOverridableSequenceIdentifiers(owner, request);
                Map overridenLayoutSequences = new HashMap();
                List equences = owner.getSequences();
                for (int i = 0; i < equences.size(); i++) {
                    Sequence sequence = (Sequence) equences.get(i);
                    String identifier = sequence.getIdentifier();
                    overridenLayoutSequences.put(identifier, (identifiers.contains(identifier)) ? Boolean.TRUE : Boolean.FALSE);
                }
                request.setAttribute("overridenLayoutSequences", overridenLayoutSequences);
            }

			if ( owner != null ) {
				Set identifiers;
				if ( owner instanceof ContentPage || (owner instanceof ActionPage && !request.isUserInRole("core-sequence-create") && !request.isUserInRole("core-sequence-update")) ) {
					identifiers = WebappUtil.getOverridableSequenceIdentifiers(owner, request);
					if ( identifiers != null && !identifiers.isEmpty() ) {
						request.setAttribute("canCreateOrUpdate", "true");
					}
				} else if ( owner instanceof Layout && !request.isUserInRole("core-sequence-create") && !request.isUserInRole("core-sequence-update") ) {
					Layout ownerLayout = (Layout) owner;
                    identifiers = WebappUtil.getOverridableSequenceIdentifiers(ownerLayout, request);
					if ( identifiers != null && !identifiers.isEmpty() ) {
						request.setAttribute("canCreateOrUpdate", "true");
					}
				} else {
                    // (it's AP or Layout and user can create/update sequences)
                    // OR (its not CP, AP or Layout)
                    if ( request.isUserInRole("core-sequence-create") || request.isUserInRole("core-sequence-update") ) {
					    request.setAttribute("canCreateOrUpdate", "true");
      				}
                }
			}
		}
	}
}